package util

import (
	//"fmt"
	"github.com/google/uuid"
	"github.com/hashicorp/consul/api"
	//"github.com/go-kit/kit/sd/consul"
	"log"
)

var ConsulClient *api.Client
type ServiceSt struct{
	ID string
	Port int
	Name string
}
var ServiceInfo ServiceSt

func RegService()  {
	reg := api.AgentServiceRegistration{}
	reg.ID = ServiceInfo.ID
	reg.Name = ServiceInfo.Name
	reg.Port = ServiceInfo.Port
	reg.Tags = []string{"primary"}

	check := api.AgentServiceCheck{
		Interval: "5s",
		HTTP: "http://lightos.cloud:8088/health",
	}

	reg.Check = &check

	//client, err := api.NewClient(config)
	//if err != nil {
	//	log.Fatal(err)
	//}
	err := ConsulClient.Agent().ServiceRegister(&reg)
	if err != nil {
		log.Fatal(err)
	}

}



func init() {//consul服务的地址
	config := api.DefaultConfig()
	config.Address = "lightos.cloud:8500"
	client, err := api.NewClient(config)
	if err != nil {
		log.Fatal("consulapi.NewClient err !", err)
	}
	ConsulClient = client
	ServiceInfo.ID = "userservice"+uuid.New().String()
}

func SetServiceNameAndPort(name string, port int)  {
	ServiceInfo.Name = name
	ServiceInfo.Port = port
}

//func RegService()  {
//	reg := api.AgentServiceRegistration{}
//	reg.ID = ServiceInfo.ID
//	reg.Name = ServiceInfo.Name
//	reg.Port = ServiceInfo.Port
//	reg.Tags = []string{"primary"}
//
//}
func UnRegService() {
	ConsulClient.Agent().ServiceDeregister(ServiceInfo.ID)
}

//func RegService1()  {
//	config := api.Config{
//		Address: "lightos.cloud:8500"
//	}
//	newClient, err := api.NewClient(config)
//	if err != nil {
//		fmt.Println("api.NewClient err ", err)
//		return
//	}
//	client := consul.NewClient(newClient)
//	client.Register()
//}
